/*
 * @Description: 角色信息面板
 * @Author: Rfan
 * @Date: 2022-03-31 14:00:56
 * @LastEditTime: 2023-02-27 09:29:46
 */

import {
  Button,
  Checkbox,
  Divider,
  Form,
  Input,
  Menu,
  message,
  Radio,
  RadioChangeEvent,
  Space,
  Typography
} from 'antd';
import classNames from 'classnames/bind';
import { useEffect, useMemo, useState } from 'react';
import { fetchFondsListByUnitId } from '@/api/fonds';
import { fetchRoleDataList, saveRoleDataList } from '@/api/role';
import { jsonClone } from '@/utils';
import { appState } from '@/store/mobx';
import { useRoleContext } from '../contexts/RoleContext';
import FunctionRightsDialog from './dialogs/FunctionRightsDialog';
import MultiDepartmentDialog from './dialogs/MutidepartmentDialog';
import type { SelectEventHandler } from 'rc-menu/lib/interface';
import type { IBaseDic } from '@/interfaces/global';
import type { IFond } from '@/interfaces/fond';
import styles from '../styles/infoPane.module.scss';

const cx = classNames.bind(styles);

const libraryTypeList: IBaseDic[] = [
  { id: 1, name: '单位资料库' },
  { id: 2, name: '部门资料库' },
  { id: 3, name: '个人资料库' }
];

const InfoPane = () => {
  const { selectRoleId, adminRoleTypeList, getRoleInfo } = useRoleContext();
  const [baseForm] = Form.useForm();

  // 角色基本信息
  const [roleInfo, setRoleInfo] = useState<any>({});
  // 全宗列表
  const [fondList, setFondList] = useState([]);
  // 选中的全宗
  const [selectFond, setSelectFond] = useState(null);
  // 数据权限列表
  const [dataRightsList, setDataRightsList] = useState([]);
  // 添加规则弹窗状态
  const [addRuleVisible, setAddRuleVisible] = useState(false);
  // 选择部门弹窗
  const [multiDepartmentVisible, setMultiDepartmentVisible] = useState(false);
  // 出入部门弹窗的部门选中内容
  const [multiSelect, setMultiSelect] = useState<any>({});
  // 数据权限保存激活标识
  const [dataFlag, setDataFlag] = useState(false);

  useEffect(() => {
    if (parseInt(selectRoleId, 10)) {
      // 获取角色基本信息
      const base = getRoleInfo(selectRoleId);
      console.log('base up', base);
      setRoleInfo(base);
      // 第一次进入时表单赋值不成功，暂时加一个延时
      setTimeout(() => {
        base && baseForm.setFieldsValue(base);
      }, 0);
      // 获取全宗列表
      fetchFondsListByUnitId(appState?.unitId).then((res) => {
        const _fondList = res.data;
        setFondList(_fondList);
        setSelectFond(`${_fondList[0].id}`);
      });
    } else {
      baseForm.resetFields();
    }
  }, [appState?.unitId, selectRoleId]);

  useEffect(() => {
    if (parseInt(selectRoleId, 10) && selectFond) {
      // // 获取角色基本信息
      // const base = getRoleInfo(selectRoleId);
      // console.log('base down', base);
      // setRoleInfo(base);
      // base && baseForm.setFieldsValue(base);

      fetchRoleDataList({ fondsId: selectFond, roleId: selectRoleId })
        .then((res) => {
          setDataRightsList(res.data);
        })
        .catch(() => {
          setDataRightsList([]);
        });
    } else {
      baseForm.resetFields();
    }
  }, [selectRoleId, selectFond]);

  /**
   * @description:Menu组件设置为受控组件，选中节点时设置选中的key并将选中的内容返回出去
   * @param {React.Key[]} selectedKeys
   */
  const changeFond: SelectEventHandler = ({ selectedKeys }) => {
    console.log('selected', selectedKeys);
    if (selectedKeys.length > 0) {
      setSelectFond(selectedKeys[0]);
    }
  };

  /**
   * @description: 切换档案类型数据权限
   * @param {RadioChangeEvent} evt 选项event
   * @param {number} id 选择的条目ID
   */
  const changeManageType = (evt: RadioChangeEvent, id: number) => {
    const list = jsonClone(dataRightsList);
    for (let i = 0; i < list.length; i++) {
      if (list[i].archiveType?.id === id) {
        list[i].dataRights.rights = evt.target.value;
        break;
      }
    }
    setDataRightsList(list);
    setDataFlag(true);
  };

  /**
   * @description: 数据权限批量处理
   * @param {number} val 选中项目的值
   * @param {boolean} isAll 是否全选，true-全选，false-反选
   */
  const multiSelectType = (val: number, isAll: boolean) => {
    const list = jsonClone(dataRightsList);
    for (let i = 0; i < list.length; i++) {
      const ele = list[i].dataRights;
      if (isAll) {
        ele.rights = val;
      } else {
        ele.rights = ele.rights !== val ? val : val === 1 ? 0 : 1;
      }
    }
    setDataRightsList(list);
    setDataFlag(true);
  };

  /**
   * @description: 打开选择部门弹窗方法
   * @param {number} id 选中的条目ID
   * @param {number} rights 弹窗对应选项的值
   */
  const openMultiDialog = (id: number, rights: number) => {
    const rightsObj = dataRightsList.find((item) => item.archiveType?.id === id)?.dataRights || {};
    if (rightsObj.rights !== undefined) {
      rightsObj.id = id;
      rightsObj.rights = rights;
    }
    setMultiSelect(rightsObj);
    setMultiDepartmentVisible(true);
  };

  /**
   * @description: 关闭选择部门弹窗，根据参数判断取消还是保存
   * @param {boolean} saveFlag 添加的规则，保存时使用
   * @param {any} params 传入的环境，用于同意参数，保存时使用
   */
  const closeMultiDialog = (saveFlag: Boolean, params?: any) => {
    if (saveFlag) {
      const list = jsonClone(dataRightsList);
      const { id } = params;
      delete params.id;
      for (let i = 0; i < list.length; i++) {
        if (list[i].archiveType?.id === id) {
          list[i].dataRights = params;
          break;
        }
      }
      setDataRightsList(list);
      setDataFlag(true);
    }
    setMultiDepartmentVisible(false);
  };

  /**
   * @description: 保存数据权限
   */
  const saveDataRights = () => {
    const data = dataRightsList.map((item) => {
      const { archiveType, dataRights, roleDataRights } = item;
      return {
        dataRights,
        id: roleDataRights?.id,
        roleId: selectRoleId,
        fondsId: archiveType.fondsId,
        archiveTypeId: archiveType.id
      };
    });
    saveRoleDataList(data).then(() => {
      message.success('保存成功');
    });
  };

  return (
    <div className={cx('info-pane')}>
      <p className="desc">设置角色的名称，可操作的功能权限和 对档案的访问权限</p>
      <Form form={baseForm} wrapperCol={{ span: 14 }} colon={false}>
        <Form.Item label="角色名称" name="roleName" extra="必须填写，可输入中文。">
          <Input />
        </Form.Item>
        <Divider />
        <Form.Item label="角色类型" name="roleType">
          <Radio.Group className={cx('role-type__group')} disabled>
            <Space direction="vertical">
              {adminRoleTypeList.map((item: any) => (
                <div key={item.id} className={cx('role-type__item')}>
                  <Radio value={item.id}>{item.name}</Radio>
                  <Typography.Text type="secondary">（{item.desc}）</Typography.Text>
                </div>
              ))}
            </Space>
          </Radio.Group>
        </Form.Item>
        <Divider />
        <Form.Item label="功能权限">
          <Form.Item noStyle>
            <Button
              disabled={!selectRoleId}
              onClick={() => {
                setAddRuleVisible(true);
              }}
            >
              点击进行设置
            </Button>
          </Form.Item>
          <span className="ant-form-item-extra"> 设置本角色可以操作的菜单项和功能项</span>
        </Form.Item>
        <Form.Item label="首页布局">
          <Form.Item noStyle>
            <Button disabled>点击进行设置</Button>
          </Form.Item>
          <span className="ant-form-item-extra"> 设置本权限我的首页展现的内容和功能</span>
        </Form.Item>
        <Divider />
      </Form>
      <Form wrapperCol={{ span: 14 }} colon={false}>
        <Form.Item label="数据权限" labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
          <div className={cx('data__table')}>
            <div className={cx('data__fond')}>
              <h6 className={cx('title')}>选择全宗</h6>
              <Menu
                items={fondList.map((fond: IFond) => ({ label: fond.fondName, key: fond.id }))}
                selectedKeys={[selectFond]}
                onSelect={changeFond}
              />
            </div>
            <div className={cx('data__archive-type')}>
              <div className={cx('data__operate')}>
                <Typography.Paragraph className={cx('data_tips')} type="secondary">
                  批量选择将快捷设置所有档案库数据权限，您也可继续分档案进行设置
                </Typography.Paragraph>
                <Space>
                  {/* <Button size="small">取消</Button> */}
                  <Button
                    size="small"
                    disabled={!dataFlag}
                    onClick={() => {
                      saveDataRights();
                    }}
                  >
                    确认
                  </Button>
                </Space>
              </div>
              <div className={cx('archive-right__list')}>
                <div className={`${cx('archive-right__item')} ${cx('archive-right__titl')}`}>
                  <Space size="large">
                    <div key="static" className={cx('archive__name')}>
                      档案类型
                    </div>
                    {dataRightsList[0] &&
                      dataRightsList[0].dataRightsOptionList
                        .filter((option: any) => option.value < 2)
                        .map((item: any) => (
                          <div key={item.value} className={cx('archive__operate')}>
                            <Button
                              size="small"
                              type="link"
                              onClick={() => {
                                multiSelectType(item.value, true);
                              }}
                            >
                              全选
                            </Button>
                            {dataRightsList[0].dataRightsOptionList.length < 3 && (
                              <>
                                /
                                <Button
                                  size="small"
                                  type="link"
                                  onClick={() => {
                                    multiSelectType(item.value, false);
                                  }}
                                >
                                  反选
                                </Button>
                              </>
                            )}
                          </div>
                        ))}
                  </Space>
                </div>
                {dataRightsList.map(({ archiveType, dataRightsOptionList, dataRights }: any) => (
                  <div key={archiveType.id} className={cx('archive-right__item')}>
                    <Space size="large">
                      <div className={cx('archive__name')}>{archiveType?.atName}</div>
                      <div className={cx('archive__choose')}>
                        <Radio.Group
                          value={dataRights?.rights}
                          onChange={(evt) => {
                            changeManageType(evt, archiveType.id);
                          }}
                        >
                          <Space size="large">
                            {dataRightsOptionList.map((rightItem: any) => {
                              const multiDepart = roleInfo.roleType === 2 && rightItem.value === 2;
                              return (
                                <div
                                  key={rightItem.value}
                                  className={`${cx('choose__item')} ${
                                    multiDepart ? cx('long-item') : ''
                                  }`}
                                >
                                  <Radio value={rightItem.value}>
                                    {rightItem.name}
                                    {multiDepart && (
                                      <Button
                                        type="link"
                                        onClick={() => {
                                          openMultiDialog(archiveType.id, rightItem.value);
                                        }}
                                      >
                                        选择
                                        {dataRights.deptIdList && dataRights.deptIdList.length > 0
                                          ? `(${dataRights.deptIdList.length})`
                                          : ''}
                                      </Button>
                                    )}
                                  </Radio>
                                </div>
                              );
                            })}
                          </Space>
                        </Radio.Group>
                      </div>
                    </Space>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </Form.Item>
        <Form.Item name="library" label="资料库权限" initialValue={[3]}>
          <Checkbox.Group disabled>
            {libraryTypeList
              .filter((type) => type.id >= roleInfo.roleType)
              .map((item) => (
                <Checkbox value={item.id} key={item.id}>
                  {item.name}
                </Checkbox>
              ))}
          </Checkbox.Group>
        </Form.Item>
        <Divider />
        <Form.Item
          label="可进入下级单位浏览档案"
          extra="某些角色因为工作关系需要进入下级单位作为普通员工进行档案浏览，系统通过设置角色拥有下级单位浏览权限来支持。"
        >
          <Radio.Group disabled>
            <Radio value={1}>可以</Radio>
            <Radio value={2}>不可以</Radio>
          </Radio.Group>
        </Form.Item>
        <Divider />
      </Form>

      {useMemo(
        () => (
          <FunctionRightsDialog
            visible={addRuleVisible}
            onClose={() => {
              setAddRuleVisible(false);
            }}
          />
        ),
        [addRuleVisible]
      )}

      {useMemo(
        () => (
          <MultiDepartmentDialog
            visible={multiDepartmentVisible}
            select={multiSelect}
            onClose={closeMultiDialog}
          />
        ),
        [multiDepartmentVisible]
      )}
    </div>
  );
};

export default InfoPane;
